package com.fms.trollalarm;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.fms.trollalarm.adapter.AlarmListAdapter;
import com.fms.trollalarm.controller.AlarmController;
import com.fms.trollalarm.object.AlarmModel;
import com.fms.trollalarm.utils.Common.IntentExtra;
import com.fms.trollalarm.utils.Common.IntentRequestCode;

public class MainActivity extends Activity {

	// Layout
	private LinearLayout llAddNew;
	private ListView lvListAlarm;

	// Adapter
	private AlarmListAdapter adapter;

	// Data
	private List<AlarmModel> alarms = new ArrayList<AlarmModel>();

	// private AlarmDBHelper dbHelper = new AlarmDBHelper(this);

	private AlarmController alarmController = new AlarmController(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewIds();
		init();
		setEvent();
	}

	private void init() {
		alarms.addAll(alarmController.getAlarms());
		adapter = new AlarmListAdapter(this, alarms);
		lvListAlarm.setAdapter(adapter);
	}

	private void setEvent() {
		llAddNew.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				long id = -1;
				startAlarmDetailsActivity(id);
			}
		});
	}

	private void findViewIds() {
		// dcClock = (DigitalClock) findViewById(R.id.dc_clock);
		llAddNew = (LinearLayout) findViewById(R.id.ll_add_new);
		lvListAlarm = (ListView) findViewById(R.id.lv_list_alarm);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case IntentRequestCode.DETAIL: {
				alarms.clear();
				alarms.addAll(alarmController.getAlarms());
				adapter.notifyDataSetChanged();
				break;
			}
			default: {
				break;
			}
			}
		}
	}

	public void startAlarmDetailsActivity(long id) {
		Intent intent = new Intent(MainActivity.this, AlarmDetailActivity.class);
		intent.putExtra(IntentExtra.ID, id);
		startActivityForResult(intent, IntentRequestCode.DETAIL);
	}

}
